<script setup lang="ts">
import {ref, inject, onMounted} from 'vue'
import {useYklibLoginStore} from 'yklib'
import {useCounterStore} from "../stores/counter";

const printToTerm = inject('printToTerm') as (text: string, lvl?: string) => void
const setTaskBar = inject('setTaskBar') as (text: string, progress?: number) => void
const store = useYklibLoginStore()
const counterStore = useCounterStore()

interface DockerImage {
  name: string;
  tag: string;
  id: string;
  size: string;
}

const images = ref<DockerImage[]>([])
const searchQuery = ref('')
const searchResults = ref<string[]>([])
const imageToInstall = ref('')
const loading = ref(false)
const error = ref('')

const fetchInstalledImages = async () => {
  try {
    setTaskBar('正在获取镜像列表', 50) // 假设获取镜像列表需要50%的进度
    loading.value = true
    // @ts-ignore
    const result = await window.pywebview.api.getDockerImages()
    if (result.suc) {
      images.value = result.images
    } else {
      error.value = result.msg
    }
  } catch (e) {
    error.value = '获取镜像列表失败'
    setTaskBar('获取镜像列表失败')
  } finally {
    loading.value = false
  }
}

const searchImages = async () => {
  if (!searchQuery.value.trim()) return

  try {
    loading.value = true
    setTaskBar('正在搜索镜像...', 10) // 假设搜索镜像需要0%的进度
    // @ts-ignore
    const result = await window.pywebview.api.searchDockerImages(searchQuery.value)
    if (result.suc) {
      searchResults.value = result.results
    } else {
      error.value = result.msg
    }
  } catch (e) {
    error.value = '搜索镜像失败'
    printToTerm(`搜索镜像失败: ${searchQuery.value}`)
  } finally {
    loading.value = false
  }
  setTaskBar(`搜索镜像失败: ${searchQuery.value}`, 0) // 假设搜索完成后进度条满
}

const installImage = async () => {
  if (!imageToInstall.value.trim()) return

  try {
    loading.value = true
    setTaskBar('正在安装镜像...') // 假设安装镜像需要50%的进度
    // @ts-ignore
    const result = await window.pywebview.api.installDockerImage(imageToInstall.value)
    if (result.suc) {
      await fetchInstalledImages()
      error.value = ''
    } else {
      error.value = result.msg
    }
  } catch (e) {
    error.value = '安装镜像失败'
  } finally {
    loading.value = false
  }
}

const removeImage = async (image: DockerImage) => {
  if (!confirm(`确定要删除镜像 ${image.name}:${image.tag} 吗？`)) {
    return;
  }

  try {
    loading.value = true;
    setTaskBar('正在删除镜像...');
    // @ts-ignore
    const result = await window.pywebview.api.remove_image(image);
    if (result.suc) {
      await fetchInstalledImages();
      error.value = '';
    } else {
      error.value = result.msg;
    }
  } catch (e) {
    error.value = '删除镜像失败';
  } finally {
    loading.value = false;
  }
}
const renameImage = async (image: DockerImage) => {
  const newName = prompt(`请输入新的镜像名称（格式：名称:标签）:`, `${image.name}:${image.tag}`);
  if (!newName) return;

  try {
    loading.value = true;
    setTaskBar('正在重命名镜像...');
    // @ts-ignore
    const result = await window.pywebview.api.rename_image(image, newName);
    if (result.suc) {
      await fetchInstalledImages();
      error.value = '';
    } else {
      error.value = result.msg;
    }
  } catch (e) {
    error.value = '重命名镜像失败';
  } finally {
    loading.value = false;
  }
}
const pushImageToRegistry = async (image: DockerImage) => {
  if (!image.name.trim()) return

  try {
    loading.value = true
    setTaskBar('正在推送镜像到仓库...') // 假设安装镜像需要50%的进度
    printToTerm(`正在推送镜像到仓库: ${image.name}`, 'info')
    // @ts-ignore
    const result = await window.pywebview.api.pushDockerImageToRegistry(image)
  } catch (e) {
  }
}

onMounted(async () => {
  await fetchInstalledImages()
})
</script>

<template>
  <div class="space-y-4">


    <div class="flex items-center space-x-2">
      <input v-model="imageToInstall" placeholder="输入要安装的镜像名称，如：hello-world:latest"
             class="border rounded px-3 py-2 w-[calc(100%-120px)]">
      <button @click="installImage"
              class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 w-[120px]">
        安装镜像
      </button>
    </div>

    <div class="flex items-center space-x-2 mt-2">
      <span class="text-sm text-gray-500">常用镜像:</span>
      <template v-for="(img, index) in ['hello-world','python','python:2.12', 'python:2.12-alpine',
      'mysql:9', 'mysql:9-alpine', 'caddy:2.10',
            'nextcloud:31', 'nextcloud:31-alpine', 'registry:3', 'klausmeyer/docker-registry-browser:1.8']"
                :key="index">
                <span @click="imageToInstall = img"
                      class="text-sm text-blue-500 hover:text-blue-700 cursor-pointer px-2 border-r border-gray-300 last:border-r-0">
                    {{ img }}
                </span>
      </template>
    </div>
    <div class="flex items-center space-x-2">
      <input v-model="searchQuery" placeholder="搜索Docker镜像" class="border rounded px-3 py-2 w-[calc(100%-120px)]"
             @keyup.enter="searchImages">
      <button @click="searchImages"
              class="bg-purple-500 text-white px-4 py-2 rounded hover:bg-purple-600 w-[120px]">
        搜索
      </button>
    </div>

    <div v-if="searchResults.length > 0" class="bg-gray-50 p-3 rounded">
      <h3 class="font-medium mb-2">搜索结果</h3>
      <ul class="space-y-1">
        <li v-for="(result, index) in searchResults" :key="index" class="text-sm">
          {{ result }}
        </li>
      </ul>
    </div>
    <div v-if="error" class="text-red-500 text-sm">
      {{ error }}
    </div>
    <div v-if="images.length > 0" class="bg-gray-50 p-3 rounded">
      <h3 class="font-medium mb-2">已安装镜像</h3>
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-100">
          <tr>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              镜像名称
            </th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              标签
            </th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              ID
            </th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              大小
            </th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              操作
            </th>
          </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
          <tr v-for="(image, index) in images" :key="index">
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ image.name }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ image.tag }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ image.id }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ image.size }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
              <button @click="removeImage(image)"
                      class="bg-red-500 hover:bg-red-700 text-white px-3 py-1 rounded text-sm mx-1"
                      title="点击删除该镜像">
                删除
              </button>
              <button @click="renameImage(image)"
                      class="bg-blue-500 hover:bg-blue-700 text-white px-3 py-1 rounded text-sm mx-1"
                      title="点击重命名该镜像">
                重命名
              </button>
              <button v-if="counterStore.hasRegistry" @click="pushImageToRegistry(image)"
                      class="bg-red-500 hover:bg-red-700 text-white px-3 py-1 rounded text-sm mx-1"
                      title="推送该镜像到私有仓库，私有仓库为运行中的 registry 容器对应的仓库">
                推送
              </button>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>

  </div>
</template>